Skip to content

Add SimGlucose Dataset, GlucoseControlTask and SACGRU for Closed-Loop Blood Glucose Control - #1773

Open
sushmit1990 wants to merge 13 commits into
sunlabuiuc:masterfrom
sushmit1990:glucose-control
Open

sushmit1990 wants to merge 13 commits into
sunlabuiuc:masterfrom
sushmit1990:glucose-control

Conversation

@sushmit1990

@sushmit1990 sushmit1990 commented Nov 30, 2026 •

Copy link
Copy Markdown

Contributors

Team G1 — Georgia Tech CSE6250: Big Data Analytics for Healthcare, Fall 2026

Contribution Type

Full Pipeline (Dataset + Task + Model)

This contribution includes a complete reinforcement learning pipeline, paper reproduction experiments, two extension/ablation studies, an executed end-to-end demonstration notebook, a runnable ablation script, API documentation, and unit tests.

Paper

Fox, I., Lee, J., Pop-Busui, R., & Wiens, J. (2020).

Deep Reinforcement Learning for Closed-Loop Blood Glucose Control.

Machine Learning for Healthcare (MLHC), Proceedings of Machine Learning Research, Volume 126.

Quick Links

1. Background and Motivation

Type 1 diabetes requires frequent blood glucose monitoring and insulin administration. Conventional basal-bolus controllers rely on patient-specific parameters, glucose measurements, and meal announcements to determine insulin dosages.

The selected paper investigates whether deep reinforcement learning can automate insulin delivery using historical continuous glucose monitoring (CGM) measurements and insulin delivery history, without requiring meal announcements as policy inputs.

We reproduce the paper's recurrent Soft Actor-Critic (SAC) approach using the authors' RL4BG simulator and integrate the complete Dataset, Task, Model, training, and evaluation pipeline into PyHealth.

We additionally investigate whether initializing the experience replay buffer with basal-bolus expert experience improves glycemic control, training stability, and online learning efficiency.

2. Implementation

The contributed pipeline follows the workflow:

SimGlucoseDataset → GlucoseControlTask → PyHealth DataLoader → Experience Replay → SACGRU Training → Policy Evaluation

2.1 Dataset: SimGlucoseDataset

SimGlucoseDataset inherits from PyHealth's BaseDataset and provides access to 30 virtual patients from the UVA/Padova Type 1 diabetes simulator:

  • 10 adults, 10 adolescents, and 10 children.
  • Patient-specific physiological parameters.
  • Basal-bolus controller parameters.
  • PID controller parameters.

Virtual patient characteristics are represented using PyHealth's Patient and Event abstractions. Unlike conventional static healthcare datasets, glucose and insulin trajectories are generated dynamically through simulator interactions.

No protected clinical datasets or additional data-access permissions are required.

2.2 Task: GlucoseControlTask

GlucoseControlTask inherits from PyHealth's BaseTask and generates reinforcement learning transitions using a basal-bolus (BB) expert controller.

Field Description Default shape
state Current glucose and insulin history (96,)
action Normalized expert insulin action (1,)
reward Simulator reward (1,)
next_state Updated glucose and insulin history (96,)
done Episode termination indicator (1,)
truncated Time-limit truncation indicator (1,)

Following the paper, the default observation contains four hours of CGM and insulin delivery history sampled at five-minute intervals.

The task supports configurable patient selection, simulation duration, observation history, random seed, reward function, and simulator history initialization.

Expert transitions are processed through PyHealth's existing DataLoader interface and transferred into an experience replay buffer.

2.3 Model: SACGRU

SACGRU inherits from PyHealth's BaseModel and implements the recurrent Soft Actor-Critic architecture described in the selected paper.

The implementation includes:

  • GRU-based stochastic Gaussian actor.
  • GRU-based Q-network.
  • GRU-based value and target value networks.
  • Automatic entropy temperature optimization.
  • Continuous action selection using tanh-squashed Gaussian actions.
  • Soft target network updates.
  • Replay-based optimization through a custom training_step() method.

The default architecture uses two GRU layers with 128 hidden units per layer. Model hyperparameters, including hidden dimensions, GRU layers, learning rates, discount factor, and target network update coefficient, are configurable.

The learned policy uses historical CGM and insulin delivery observations without requiring meal announcements during execution.

2.4 Reinforcement Learning Integration Challenges

PyHealth's standard training workflow is primarily designed around static samples, feature-label pairs, and supervised optimization. In contrast, reinforcement learning generates experience dynamically through interactions between an agent and its environment.

To accommodate this difference, we use the Dataset and Task abstractions to generate expert transitions, a replay buffer to combine expert and online experience, and a custom SAC training loop with multiple optimizers, entropy tuning, and target network updates. Evaluation uses independent closed-loop simulator rollouts rather than static labeled test samples.

This design integrates reinforcement learning without modifying PyHealth's underlying BaseDataset, BaseTask, BaseModel, or Trainer implementations, providing a reference example for future simulator-based healthcare reinforcement learning contributions.

3. End-to-End Demonstration Notebook

[Glucose Control End-to-End Demo Notebook](https://github.com/sushmit1990/PyHealth/blob/glucose-control/examples/glucose_control/glucose_control_end_to_end_demo.ipynb)

The executed Jupyter notebook demonstrates the complete integration of the three contributed PyHealth components, with explanatory text, saved execution outputs, and visualizations.

The notebook covers:

  1. Loading virtual patient parameters using SimGlucoseDataset.
  2. Generating basal-bolus expert transitions using GlucoseControlTask.
  3. Inspecting transition fields and DataLoader tensor dimensions.
  4. Initializing the experience replay buffer with expert transitions.
  5. Initializing and training SACGRU through online simulator interactions and replay-based optimization.
  6. Evaluating the trained policy using deterministic actions and an independent simulation seed.
  7. Visualizing training behavior, glucose trajectories, and insulin delivery.

The CPU-friendly notebook uses adult#001, 288 expert transitions, 288 online training steps, 257 gradient updates, and a one-day independent evaluation.

The notebook successfully completed the entire pipeline using the actual RL4BG simulator. Its purpose is to demonstrate functional integration and explain the reinforcement learning workflow rather than train a converged glucose control policy.

4. Reproduction Experimental Setup

We reproduce the paper's RL-Scratch controller for two virtual patients, adult#001 and child#001, selected from the authors' hyperparameter tuning subset.

Due to computational and time constraints, we use one training seed per configuration while retaining the original online training budget.

Parameter Configuration
Observation history 4 hours
Sampling interval 5 minutes
Observation dimensions 96
GRU architecture 2 layers, 128 hidden units
Optimizer Adam
Learning rate 0.0003
Discount factor 0.99
Target network update coefficient 0.005
Replay buffer capacity 1,000,000
Batch size 256
Online warmup 5,760 steps
Training epochs 300
Online steps per epoch 5,760 (20 simulated days)
Total online training steps 1,728,000
Total gradient updates 1,722,241
Validation horizon 2,880 steps (10 simulated days)
Independent evaluation 100 ten-day rollouts per configuration
Training seed 1

Checkpoint Selection and Evaluation

After each training epoch, the policy is evaluated deterministically using a separate validation environment.

The checkpoint with the lowest mean validation Magni risk is retained among checkpoints satisfying both conditions:

  • Completion of the entire 2,880-step validation rollout.
  • Simulated blood glucose remaining within 30–1000 mg/dL.

Final evaluation uses 100 independent ten-day rollouts with test seeds 2000001–2000100, matched across configurations and excluded from checkpoint selection.

5. Reproduction Results

We compare patient-specific median Magni risk against approximate values visually extracted from the original paper's figures.

Lower Magni risk is better.

Patient Controller Paper (approx.) Reproduction
adult#001 BB 12.0 8.60
adult#001 RL-Scratch 7.8 9.32
child#001 BB 24.4 21.44
child#001 RL-Scratch 11.7 10.56

The reproduction captures the substantially poorer BB performance for the selected child patient and the improvement obtained through reinforcement learning for that patient.

The adult RL-Scratch controller underperforms the approximate published result, while the child RL-Scratch controller achieves a broadly comparable median risk.

Differences may arise from the limited number of training seeds, implementation differences, and the BB evaluation protocol.

We restrict the direct paper comparison to patient-specific median Magni risk because the paper's aggregate glycemic range statistics across 30 patients are not directly comparable to our patient-specific results.

6. Extension and Ablation Studies

Our extension investigates whether initializing the experience replay buffer with expert-generated transitions improves reinforcement learning performance.

The extension changes the initial replay data rather than introducing supervised weight pretraining or imitation learning. Model parameters remain randomly initialized, and the SAC algorithm is retained.

Expert experience is generated using the contributed Dataset and Task and processed through PyHealth's DataLoader.

6.1 Ablation I: Expert Replay Initialization

Both adult and child patients are evaluated under two configurations:

Configuration Initial expert transitions
RL-Scratch 0
RL-Expert 5,760

The 5,760 expert transitions correspond to 20 simulated days of basal-bolus controller experience.

Both configurations receive the same online training budget, gradient-update budget, replay capacity, and model architecture.

6.2 Ablation II: Expert Replay Quantity

For the adult patient, we additionally investigate filling the entire replay buffer before online training.

Configuration Initial expert transitions Initial buffer occupancy
RL-Scratch 0 0%
RL-Expert 5,760 0.576%
RL-Expert Full Buffer 1,000,000 100%

The full replay buffer is initialized using 35 bounded expert simulation trajectories.

This experiment investigates whether increasing the quantity of initial expert experience improves online learning efficiency and final policy performance while retaining the same online interaction and gradient-update budgets.

7. Full Experimental Results

The following metrics are arithmetic means across 100 independent ten-day test rollouts per configuration.

  • Magni risk: Risk associated with hypo- and hyperglycemia.
  • TIR: Percentage of time within 70–180 mg/dL.
  • TBR: Percentage of time below 70 mg/dL.
  • TAR: Percentage of time above 180 mg/dL.

7.1 Independent Test Performance

Patient Controller Magni Risk ↓ TIR (%) ↑ TBR (%) ↓ TAR (%) ↓
Adult BB 8.70 67.82 3.34 28.83
Adult RL-Scratch 9.79 64.27 5.50 30.23
Adult RL-Expert 6.46 68.29 0.36 31.35
Adult RL-Expert Full Buffer 7.73 63.45 0.65 35.90
Child BB 21.45 52.41 17.83 29.75
Child RL-Scratch 10.60 70.62 3.26 26.12
Child RL-Expert 11.54 64.20 2.03 33.77

All seven configurations completed 100 independent test rollouts. No catastrophic failures, defined as simulated blood glucose below 5 mg/dL, were observed under this evaluation protocol.

7.2 Training Performance and Stability

Patient Controller Best epoch Best validation risk Training terminations Eligible validation epochs
Adult RL-Scratch 120 6.65 1,687 123/300
Adult RL-Expert 164 6.10 900 194/300
Adult RL-Expert Full Buffer 95 6.20 1,481 175/300
Child RL-Scratch 190 9.81 5,728 127/300
Child RL-Expert 208 9.82 7,922 153/300

7.3 Findings: Expert Replay Initialization

For the adult patient, RL-Expert relative to RL-Scratch achieved:

  • 34.0% reduction in mean test Magni risk.
  • 93.5% reduction in time below range.
  • 4.02 percentage-point improvement in time in range.
  • 46.7% reduction in training episode terminations.
  • Lower Magni risk across all 100 matched test seeds.

For the child patient, RL-Expert achieved:

  • 37.7% reduction in time below range.
  • 8.9% increase in mean test Magni risk.
  • 6.42 percentage-point reduction in time in range.
  • Increased time above range.

The results suggest a patient-specific trade-off: expert replay initialization can reduce hypoglycemia without necessarily improving overall glucose control.

7.4 Findings: Expert Replay Quantity

For the adult patient, full-buffer initialization reached an eligible validation Magni risk of 6.5 or lower substantially earlier than standard expert initialization.

Configuration First eligible epoch with risk ≤ 6.5 Online interaction steps
RL-Scratch Not achieved Not achieved
RL-Expert 164 944,640
RL-Expert Full Buffer 69 397,440

Full-buffer initialization required approximately 58% fewer online interactions to reach this threshold.

However, it required substantially more expert-generated data and produced approximately 19.6% higher final mean test Magni risk than standard expert initialization.

Increasing initial expert experience therefore improved early online learning efficiency for the selected threshold but did not improve final held-out policy performance.

This improvement should not be interpreted as improved total sample efficiency because expert generation introduces substantial additional simulation cost.

7.5 Experimental Scope

The complete experimental study comprises:

  • Five full reinforcement learning training runs.
  • Two basal-bolus baseline evaluations.
  • Seven evaluated configurations.
  • 700 independent ten-day test rollouts.

Detailed experimental configurations, results, and limitations are available in:

[RESULTS.md](https://github.com/sushmit1990/PyHealth/blob/glucose-control/examples/glucose_control/RESULTS.md)

8. Runnable Python Ablation Example

[simglucose_glucose_control_sacgru.py](https://github.com/sushmit1990/PyHealth/blob/glucose-control/examples/simglucose_glucose_control_sacgru.py)

The CPU-friendly example demonstrates the complete pipeline and compares three replay initialization configurations.

Parameter Scratch Expert Full Buffer
Initial expert transitions 0 288 2,880
Replay capacity 2,880 2,880 2,880
Initial buffer occupancy 0% 10% 100%
Online training steps 288 288 288
Gradient updates 257 257 257
Evaluation steps 288 288 288
GRU hidden size 32 32 32
GRU layers 1 1 1
Batch size 32 32 32
Training seed 1 1 1

All configurations use the same online training budget, gradient-update budget, model initialization seed, and independent evaluation seed.

Demonstration Results

Metric Scratch Expert Full Buffer
Magni risk 44.147 44.147 44.147
TIR (%) 27.431 27.431 27.431
TBR (%) 0.000 0.000 0.000
TAR (%) 72.569 72.569 72.569
Training terminations 4 4 4
Evaluation completed Yes Yes Yes

All three configurations successfully completed training and evaluation using the actual RL4BG simulator.

The short demonstration produces identical glycemic metrics across configurations. These results validate functional execution of the ablation pipeline rather than demonstrate converged policy performance.

The substantive scientific comparisons are obtained from the full-scale experiments in Section 7.

The notebook and Python script serve complementary purposes: the notebook explains the complete workflow with visualizations, while the script systematically executes and compares multiple replay initialization configurations.

9. Installation and Quick Start

Complete installation, training, evaluation, and visualization instructions are available in:

[Installation and Reproduction README](https://github.com/sushmit1990/PyHealth/blob/glucose-control/examples/glucose_control/README.md)

The simulator setup helper downloads a pinned version of the authors' RL4BG repository and automatically applies the required NumPy compatibility patches.

Pinned RL4BG commit:

c9e2189d44566d195bacb2e2d3b6d3a9aed1faed

The external simulator is not redistributed in this PR.

Step 1: Obtain the contribution

git clone -b glucose-control https://github.com/sushmit1990/PyHealth.git
cd PyHealth

Step 2: Create a Python environment

conda create -n pyhealth-glucose python=3.12 -y
conda activate pyhealth-glucose

Step 3: Install dependencies and the simulator

Install the compatible CPU PyTorch and torchvision versions specified in the README, then execute the following commands from the repository root:

python -m pip install -r examples/glucose_control/requirements_glucose_control.txt
python -m pip install -e . --no-deps
python examples/glucose_control/setup_rl4bg.py --target .
python -m pip check

The setup helper installs the pinned external simulator and applies compatibility fixes.

No protected clinical data or manual simulator modifications are required.

Step 4: Run the CPU ablation example

python examples/simglucose_glucose_control_sacgru.py

The script trains and evaluates Scratch, Expert, and Full Buffer configurations and prints a comparative table of glucose control metrics.

Step 5: Run the end-to-end notebook

python -m pip install ipykernel ipywidgets

Open:

examples/glucose_control/glucose_control_end_to_end_demo.ipynb

Select the pyhealth-glucose environment as the notebook kernel in VS Code or Jupyter and execute all cells sequentially.

Full Reproduction Experiments

Example commands for adult patient training:

python examples/glucose_control/train_epochs.py --patient "adult#001" --policy scratch --device cuda
python examples/glucose_control/train_epochs.py --patient "adult#001" --policy expert --device cuda
python examples/glucose_control/train_epochs_full_expert.py --patient "adult#001" --device cuda

The README provides the complete commands for both virtual patients, independent checkpoint evaluation, BB baseline evaluation, plotting, dependency installation, and descriptions of the generated output files.

The full experiments require substantially more computation and storage than the lightweight CPU demonstration.

10. Files for Review

Primary Implementation

File Description
pyhealth/datasets/simglucose_data.py SimGlucoseDataset implementation
pyhealth/datasets/configs/simglucose.yaml Virtual patient dataset configuration
pyhealth/tasks/glucose_control.py Expert transition generation and task schema
pyhealth/models/sac_gru.py Recurrent Soft Actor-Critic implementation

API Documentation

  • docs/api/datasets/pyhealth.datasets.SimGlucoseDataset.rst
  • docs/api/tasks/pyhealth.tasks.GlucoseControlTask.rst
  • docs/api/models/pyhealth.models.SACGRU.rst

The corresponding documentation indices and package exports have also been updated.

Unit Tests

  • tests/core/test_simglucose_data.py
  • tests/core/test_glucose_control_task.py
  • tests/core/test_sac_gru.py

Examples and Experimental Documentation

File Description
examples/simglucose_glucose_control_sacgru.py Runnable CPU ablation example
examples/glucose_control/glucose_control_end_to_end_demo.ipynb Executed end-to-end tutorial
examples/glucose_control/README.md Installation and reproduction instructions
examples/glucose_control/RESULTS.md Experimental results and analysis

Training, Evaluation, and Supporting Utilities

All files below are located under examples/glucose_control/.

File Description
train_epochs.py Full Scratch and Expert training
train_epochs_full_expert.py Full-buffer initialization experiment
evaluate_checkpoint.py Independent RL policy evaluation
evaluate_bb.py Basal-bolus baseline evaluation
plot_results.py Training and validation visualization
expert_replay.py Expert replay initialization
replay_buffer.py Circular experience replay storage
evaluate.py Shared evaluation and glucose metrics
utils.py Simulator initialization and CSV utilities
setup_rl4bg.py Pinned simulator installation
requirements_glucose_control.txt Experiment dependencies

11. Testing and Validation

All three contributed components include dedicated unit tests using synthetic patient data, mocked simulator components, and synthetic tensors.

Unit Test Coverage

Component Executable statements Statement coverage
SimGlucoseDataset 8 100%
GlucoseControlTask 67 100%
SACGRU 203 100%
Total 278 100%

All 29 unit tests and five subtests passed after integrating upstream master. The local coverage report showed 278/278 executable statements covered across the three contributed implementation files.

The tests cover patient loading and parameter parsing, task configuration and transition generation, termination and truncation behavior, model initialization, observation shapes, action selection, SAC losses, target network updates, and the complete optimization step.

Additional Validation

  • Successful Dataset, Task, and Model imports through PyHealth.
  • Successful execution of the end-to-end demonstration notebook using the actual RL4BG simulator.
  • Successful execution of all three Python ablation configurations.
  • Successful post-merge unit testing and component-specific coverage verification.
  • Identical lightweight ablation results before and after upstream integration.
  • Ruff formatting and linting checks on the contributed example scripts.
  • Successful contribution-specific whitespace validation.
  • Successful local PyHealth PR contribution rules check.

The notebook was executed before upstream integration. The Python ablation script was executed both before and after integration, with the post-merge execution reusing cached expert transitions.

Test Command

python -m pytest tests/core/test_simglucose_data.py tests/core/test_glucose_control_task.py tests/core/test_sac_gru.py -v --cov=pyhealth --cov-report=

Component-specific coverage report:

python -m coverage report --include="*simglucose_data.py,*glucose_control.py,*sac_gru.py" -m

PR compliance verification:

python tools/check_pr_rules.py --base upstream/master --head HEAD

Result:

All PR contribution rules passed.

These results reflect local validation. Repository CI and maintainer review remain separate from the local checks.

12. Limitations and Differences from the Original Paper

  • Full-scale reproduction is limited to two of the 30 virtual patients and one training seed per configuration.
  • Independent test rollouts characterize the trained policies but do not capture training-seed variability.
  • Published patient-specific risk values are approximate visual estimates from the original paper's figures.
  • We follow the released simulator's BG-based reward implementation where it differs from the paper's CGM-based description.
  • The BB evaluation protocol may differ from the original paper.
  • Differences in random seed initialization order across experimental runs may impact results.
  • The lightweight examples demonstrate functional integration rather than policy convergence.
  • Installation and execution were validated on Windows. Cross-platform compatibility has not been independently verified.
  • All experiments are simulation-based; no clinical validation was performed.

The implemented pipeline can be reviewed and executed without requiring access to protected patient datasets.

@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 88.81% (61716 / 69491 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 95 / 95
pyhealth/datasets/simglucose_data.py 100.00% 8 / 8
pyhealth/models/__init__.py 100.00% 132 / 132
pyhealth/models/sac_gru.py 100.00% 203 / 203
pyhealth/tasks/__init__.py 98.66% 147 / 149
pyhealth/tasks/glucose_control.py 100.00% 67 / 67

Workflow run · 2f20e72

@solarsys solarsys added the status: manual Pending maintainer's review label Dec 1, 2026
@solarsys

solarsys commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: the diff is about 374,000 characters, over the AI review's 200,000-character limit, so the review can't run on it. Everything else is inside the allowed folders, and the shared files only get registration lines, which is good.

To make it eligible for automatic review: split it into smaller PRs, each well under the limit:

  1. SimGlucoseDataset (with its config) and GlucoseControlTask, with their tests and docs pages.
  2. The SACGRU model, with its tests and docs page.
  3. The examples. A short runnable script plus the README is enough. Please trim the 130-line pinned requirements_glucose_control.txt to the few packages the example actually needs beyond PyHealth, and consider leaving out the executed notebook, which is about a quarter of the diff.

Keep the bgp imports optional as you have them now, with a clear message that points to setup_rl4bg.py. We'll then switch each part to status: automatic and request an AI review.

@sushmit1990

Copy link
Copy Markdown
Author

Why this PR has status: manual: the diff is about 374,000 characters, over the AI review's 200,000-character limit, so the review can't run on it. Everything else is inside the allowed folders, and the shared files only get registration lines, which is good.

To make it eligible for automatic review: split it into smaller PRs, each well under the limit:

  1. SimGlucoseDataset (with its config) and GlucoseControlTask, with their tests and docs pages.
  2. The SACGRU model, with its tests and docs page.
  3. The examples. A short runnable script plus the README is enough. Please trim the 130-line pinned requirements_glucose_control.txt to the few packages the example actually needs beyond PyHealth, and consider leaving out the executed notebook, which is about a quarter of the diff.

Keep the bgp imports optional as you have them now, with a clear message that points to setup_rl4bg.py. We'll then switch each part to status: automatic and request an AI review.

Hello,
Thank you for reviewing our contribution and clarifying the automatic review size limit.
This PR is also our final project submission for Georgia Tech's CSE6250 Reproducibility Challenge, which requires one PR per team. We submitted the complete Dataset–Task–Model pipeline together with the reproduction experiments and ablation studies to satisfy the full-pipeline requirements.

We are happy to split the contribution into the three smaller PRs as suggested.

Would it be acceptable to preserve this original PR for course grading evaluation and create the smaller PRs separately for upstream review?

Thank you again for your guidance.

@jhnwu3

jhnwu3 commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

/review

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

AI Review

suggestion: not available
decision: not available

This PR is too large for AI review (over 300 files or 200000 diff characters). The label stays as it is: you can make the PR smaller, for example by clearing notebook outputs or splitting it, and comment /review again, or a maintainer can review it as it is.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants